'''
Created 7/12/12
Modified 7/12/12

Uses Whole Brain Catalog (WBC) classes and tools to acquire 3D volumetric data and write to pickle files for further analysis and representation of the data.

Run via jython
@author: drlittle
'''

# import Java class
from java.net import URI

# import Java classes from WBC
from org.wholebrainproject.wbc.data.importer import SparseValueVolumeImporter
from org.wholebrainproject.wbc.generated.sparsevaluevolume import SparseValueVolume

import pickle

'''
SCRIPT BEGINS HERE
'''

# uri to obtain gene expression sparse value volume data from Allen Brain Institute via INCF ABA hub process
svv_uri_string = "http://incf-dev-local.crbs.ucsd.edu/aba/atlas?service=WPS&version=1.0.0&request=Execute&Identifier=GetGeneExpressionByGeneId&DataInputs=geneIdentifier=Coch&RawDataOutput=SparseValueVolumeXML" 

# instantiate Java uri object
svv_uri = URI(svv_uri_string)
print 'uri:', svv_uri.toString()

# instantiate WBC importer
svv_importer = SparseValueVolumeImporter(svv_uri)

# get SparseValueVolume object
sparse_value_volume = svv_importer.getData()

# svv comment string
print 'Sparse Value Volume comment:', sparse_value_volume.getComment()

# get all svv data
sparse_volume_data_type = sparse_value_volume.getSparseVolumeData()

# get list of svv datum (x, y, z, value)
datum_type = sparse_volume_data_type.getData()

# get number of data points
print 'Counting data points'
n = 0
for svd in datum_type:
    n += 1
    
# create arrays for x, y, z coordinates (integers) and values (float)
print 'Creating arrays'
x = [ 0 for i in range(n) ]
y = [ 0 for i in range(n) ]
z = [ 0 for i in range(n) ]
value = [ 0. for i in range(n) ]

# fill in coordinates and values
print 'Filling non-zero values'
i = 0
for svd in datum_type:
    x[i] = svd.getX()
    y[i] = svd.getY()
    z[i] = svd.getZ()
    value[i] = svd.getValue()
    i += 1

print 'x', x
print 'y', y
print 'z', z
print 'value', value

# pickle arrays
print 'Pickling 3dDataX.pkl'
output = open('3dDataX.pkl', 'wb')
pickle.dump(x, output)
output.close()
print 'Pickling 3dDataY.pkl'
output = open('3dDataY.pkl', 'wb')
pickle.dump(y, output)
output.close()
print 'Pickling 3dDataZ.pkl'
output = open('3dDataZ.pkl', 'wb')
pickle.dump(z, output)
output.close()
print 'Pickling 3dDataValue.pkl'
output = open('3dDataValue.pkl', 'wb')
pickle.dump(value, output)
output.close()

